package com.codejoys.monitor.web;

import com.codejoys.monitor.domain.User;
import com.codejoys.monitor.dto.BaseResult;
import com.codejoys.monitor.dto.SysUser;
import com.codejoys.monitor.exception.SysException;
import com.codejoys.monitor.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @PostMapping("/admin/modifyPass")
    public BaseResult modifyPass(
            @RequestParam("pass") String pass,
            @RequestParam("oldPass") String oldPass,
            Authentication auth) {
        String name = auth.getName();
        final SysUser tmsUser = userService.findUserByName(name);

        boolean matches = passwordEncoder.matches(oldPass, tmsUser.getPassword());
        if (!matches) {
            throw new SysException(10000, "原密码错误！");
        }

        // 密码要加密
        tmsUser.setPassword(passwordEncoder.encode(pass));

        userService.modifyPass(tmsUser);

        return BaseResult.success();
    }

    @PostMapping("/admin/register")
    public BaseResult register(User user) {
        // 密码要加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setAccount(user.getName());
        user.setCreated(new Date());
        user.setUpdated(new Date());

        userService.register(user);

        return BaseResult.success();
    }

    @GetMapping("/admin/current-user")
    public BaseResult currentUser(Authentication auth) {
        String name = auth.getName();

        final SysUser tmsUser = userService.findUserByName(name);

        final Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

        // ["admin", "teacher"]
        final Object[] roles = authorities.stream()
                .map(authority -> {
                    // ROLE_
                    return authority.getAuthority().replace("ROLE_", "");
                })
                .toArray();

        Map<String, Object> userData = new HashMap<>();
        userData.put("username", name);
        userData.put("id", tmsUser.getId());
        userData.put("roles", roles);
        userData.put("phone", tmsUser.getPhone());

        BaseResult result = BaseResult.success();
        result.setData(userData);

        return result;
    }
}
